const express = require("express");
const Result = require("../../models/Result");
const { decoded } = require("../../utils/index");
const { PRIVATE_KEY, JWT_EXPIRED } = require("../../utils/constant");
const {
  login,
  getUserInfo,
  getUserList,
  getTotalCount,
  editUser,
  createUser,
  getUserListByNameOrCardId,
  deleteUser,
  allUser,
} = require("../../services/user");
const jwt = require("jsonwebtoken");
const qiniu = require("qiniu");
const request = require("request");
const jwtAuth = require("../jwt");
const { getRoleById } = require("../../services/role");
const { getMenuList } = require("../../services/menu");
// 注册路由
const router = express.Router();
router.use(jwtAuth);

// 登录接口
router.post("/login", function (req, res) {
  const { cardId, password } = req.body;
  login(cardId, password)
    .then((user) => {
      if (!user || user.length === 0) {
        new Result("账号或密码错误，请联系管理员重试").fail(res);
      } else {
        // 生成token
        const token = jwt.sign({ cardId }, PRIVATE_KEY, {
          expiresIn: JWT_EXPIRED,
        });
        new Result(token, "登陆成功").success(res);
      }
    })
    .catch((err) => {
      new Result("登陆失败").fail(res);
    });
});

//获取用户信息接口
router.get("/getUserInfo", function (req, res, next) {
  const decode = decoded(req);
  if (decode && decode.cardId) {
    // 如果从token中读取到了username
    getUserInfo(decode.cardId).then((user) => {
      // 如果查询到username在数据库中
      if (user) {
        user.password = "***"; // 把password字段替换成***
        new Result(user, "用户信息查询成功").success(res);
      } else {
        new Result("用户信息查询失败").fail(res);
      }
    });
  } else {
    new Result("用户信息查询失败").fail(res);
  }
});

router.get("/getUserListByNameOrCardId", function (req, res, next) {
  try {
    const { searchValue } = req.query; // 获取查询条件
    if (!searchValue || searchValue.trim() === "") {
      new Result([], "用户列表查询成功").success(res);
    } else {
      getUserListByNameOrCardId(searchValue).then((data) => {
        data.forEach((item) => {
          item.label = item.userName + " " + item.cardId;
          item.value = item.id;
          delete item.userName;
          delete item.cardId;
          delete item.id;
        });
        new Result(data, "用户列表查询成功").success(res);
      });
    }
  } catch (error) {
    new Result("操作失败").fail(res);
  }
});

router.get("/list", function (req, res, next) {
  const { pageNum, pageSize } = req.query;
  getUserList(req.query).then((data) => {
    // 把data的每个元素的password字段替换成***
    data.forEach((item) => {
      item.password = "***";
    });
    getTotalCount(req.query).then((total) => {
      new Result(
        {
          list: data,
          page: {
            pageNum,
            pageSize,
            total: total.totalCount,
          },
        },
        "用户列表查询成功"
      ).success(res);
    });
  });
});

//编辑用户接口
router.post("/edit", function (req, res, next) {
  editUser(req.body)
    .then((data) => {
      new Result("操作成功").success(res);
    })
    .catch((err) => {
      new Result("操作失败").fail(res);
    });
});

//创建用户接口
router.post("/create", function (req, res, next) {
  createUser(req.body)
    .then((data) => {
      new Result("操作成功").success(res);
    })
    .catch((err) => {
      new Result("操作失败").fail(res);
    });
});

//删除用户接口
router.post("/delete", function (req, res, next) {
  const userIds =
    typeof req.body.userIds === "string"
      ? JSON.parse(req.body.userIds)
      : req.body.userIds;
  deleteUser(userIds)
    .then((data) => {
      new Result("操作成功").success(res);
    })
    .catch((err) => {
      new Result("操作失败").fail(res);
    });
});

//获取所有用户接口
router.get("/allList", function (req, res, next) {
  allUser()
    .then((data) => {
      data.forEach((item) => {
        item.password = "***";
      });
      new Result(data, "用户列表查询成功").success(res);
    })
    .catch((err) => {
      new Result("操作失败").fail(res);
    });
});

// 生成权限树
const getPermissionTree = (menuList, _permissionList) => {
  // 过滤出一级菜单
  const menuTree = [];

  // 处理一级菜单
  menuList.forEach((menu) => {
    if (menu.menuType === 1 && _permissionList.includes(menu.id)) {
      menuTree.push({ ...menu, children: [], buttons: [] });
    }
  });

  // 处理二级菜单
  menuList.forEach((menu) => {
    if (menu.menuType === 2 && _permissionList.includes(menu.id)) {
      menuTree.forEach((item) => {
        if (item.id === menu.parentId) {
          item.children.push(menu);
          item.buttons.push(menu);
        }
      });
    }
  });

  menuTree.forEach((item) => {
    if (item.parentId && item.parentId !== null) {
      menuTree.forEach((item2) => {
        if (item2.id === item.parentId) {
          item2.children.push(item);
        }
      });
    }
  });

  return menuTree.filter((menu) => !menu.parentId || menu.parentId === null);
};

//获取用户所具有的权限列表接口
router.get("/getPermissionList", async function (req, res, next) {
  const decode = decoded(req);
  if (decode && decode.cardId) {
    // 如果从token中读取到了username
    const userInfo = await getUserInfo(decode.cardId);
    const roleInfo = await getRoleById(userInfo.roleId);
    const _permissionList = JSON.parse(roleInfo.halfCheckedKeys).concat(
      JSON.parse(roleInfo.checkedKeys)
    );
    const permissionList = await getMenuList({ menuState: 1 });
    const buttonList = [];
    permissionList.forEach((menu) => {
      if (_permissionList.includes(menu.id) && menu.menuType === 2) {
        buttonList.push(menu.menuCode);
      }
    });
    new Result(
      {
        menuList: getPermissionTree(permissionList, _permissionList),
        buttonList,
      },
      "用户权限查询成功"
    ).success(res);
  } else {
    new Result("用户权限查询失败").fail(res);
  }
});

router.get("/getUploadToken", function (req, res, next) {
  try {
    const accessKey = "32284819A84514E1";
    request(
      {
        url: "http://api-driver.marsview.cc/api/users/login",
        method: "POST",
        json: true,
        body: {
          userName: "echo",
          userPwd: "377875",
        },
        headers: {
          icode: accessKey,
        },
      },
      (error, response, body) => {
        new Result(
          { token: body.data, icode: accessKey },
          "上传Token获取成功"
        ).success(res);
      }
    );
  } catch (error) {
    new Result("图片上传Token获取失败").fail(res);
  }
});

//七牛云获取上传token接口
// const accessKey = 'MsQcw7_vzGcHMcpzmB60noPAX4RtYdEohTXkBtIX'
// const secretKey = 'FOZHOS6McIS5QJ0QGQpAiOsNDFKW_UVT0hO1fLzQ'
// const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
// router.get('/uploadToken', function(req, res, next) {
//   const options = {
//     scope: 'tangweize-img'
//   }
//   const putPolicy = new qiniu.rs.PutPolicy(options)
//   const token = putPolicy.uploadToken(mac)  // 向七牛云后台发送了一个接口
//   new Result(token, '获取成功').success(res)
// })

module.exports = router;
